package org.dromara.third.convert.util;

import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.system.service.IDepartmentService;
import org.dromara.system.service.IPersonRecordService;
import org.dromara.third.auth.beans.constans.ExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;

/**
 * 存在性验证工具类
 */
@Slf4j
@Component
public class ExistenceValidator {

    private static IDepartmentService departmentService;
    private static IPersonRecordService personRecordService;

    @Autowired
    public void setDeptService(IDepartmentService departmentService) {
        ExistenceValidator.departmentService = departmentService;
    }

    @Autowired
    public void setUserService(IPersonRecordService personRecordService) {
        ExistenceValidator.personRecordService = personRecordService;
    }

    private ExistenceValidator() {
        // 工具类，防止实例化
    }

    /**
     * 验证部门存在性
     */
    public static void validateDeptExists(String deptId, String fieldName, Errors errors) {
        validateExistence(deptId, fieldName, errors, "部门",
            id -> departmentService.checkDepartmentExists(Long.valueOf(id)));
    }

    /**
     * 验证人员存在性
     */
    public static void validateUserExists(String userId, String fieldName, Errors errors) {
        validateExistence(userId, fieldName, errors, "人员",
            id -> personRecordService.checkPersonRecordExists(Long.valueOf(id)));
    }

    /**
     * 通用存在性验证方法
     */
    private static void validateExistence(String id, String fieldName, Errors errors,
                                          String entityType, ExistenceChecker checker) {
        if (StringUtils.isEmpty(id)) {
            return;
        }

        try {
            // 验证ID格式
            if (!isValidLong(id)) {
                errors.reject(String.valueOf(ExceptionEnum.AuthException06.getCode()), fieldName + "格式不正确");
                return;
            }
            // 验证存在性
            if (!checker.checkExists(id)) {
                errors.reject(String.valueOf(ExceptionEnum.AuthException06.getCode()), fieldName + "不存在");
            }
        } catch (Exception e) {
            log.error("验证{}存在性系统异常, {}Id: {}, fieldName: {}", entityType, entityType, id, fieldName, e);
            throw new BusinessServiceException(ExceptionEnum.AuthException10.getCode(), ExceptionEnum.AuthException10.getMessage());
        }
    }

    /**
     * 验证是否为有效的Long类型
     */
    private static boolean isValidLong(String value) {
        if (value == null || value.trim().isEmpty()) {
            return false;
        }
        try {
            Long.parseLong(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 存在性检查函数式接口
     */
    @FunctionalInterface
    private interface ExistenceChecker {
        boolean checkExists(String id);
    }
}
